#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <jsoncpp/json/json.h>
#include <memory>

using namespace std;

// g++ json.cc -o json.out -ljsoncpp

// 序列化
void serialize()
{
    string name = "张三";
    int age = 20;
    vector<double> score = {66, 77, 88, 99};

    Json::Value root;
    root["姓名"] = name;
    root["年龄"] = age;
    for(auto &it : score)
    {
        root["成绩单"].append(it);
    }

    Json::StreamWriterBuilder swb;
    unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    stringstream ss;
    sw->write(root, &ss);
    cout << ss.str() << endl;
}

// 反序列化
void deserialize()
{
    // R"(...)"表示...字符串，无须对...中的"进行转意
    string str = R"({"姓名":"李四", "年龄":20, "成绩单":[66.6, 77.7, 88.8, 99.9]})";

    Json::Value root;
    Json::CharReaderBuilder crb;
    unique_ptr<Json::CharReader> cr(crb.newCharReader());
    string err;
    bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &root, &err);
    if(ret == false)
    {
        cout << "字符串解析失败：" << err << endl;
        return;
    }
    cout << root["姓名"].asString() << endl;
    cout << root["年龄"].asInt() << endl;
    int size = root["成绩单"].size();
    for(int i = 0; i < size; ++i)
    {
        cout << root["成绩单"][i] << endl;
    }
}

int main()
{
    //serialize();
    deserialize();

    return 0;
}